package com.yoomiito.app.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.FrameLayout;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.GridLayoutHelper;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yoomiito.app.Constant;
import com.yoomiito.app.MainActivity;
import com.yoomiito.app.R;
import com.yoomiito.app.act.NewFreeBuyActivity;
import com.yoomiito.app.adapter.goods.detail.GoodsDetailTitleAdapter;
import com.yoomiito.app.adapter.home.reommend.EmptyAdapter;
import com.yoomiito.app.adapter.home.reommend.FeaturedAreaAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeActAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeBannerAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeBaoPinAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeBaoPinItemAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeChosenGoodsAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeHotAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeIconAdapter;
import com.yoomiito.app.adapter.home.reommend.HomePanicBuyTitleAdapter;
import com.yoomiito.app.adapter.home.reommend.HomePanicGoodsAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeVideoClipAdapter;
import com.yoomiito.app.adapter.home.reommend.HomeVipAdapter;
import com.yoomiito.app.adapter.home.reommend.HotActTitleAdapter;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseLazyFragment;
import com.yoomiito.app.base.WebViewActivity;
import com.yoomiito.app.model.CreditCard;
import com.yoomiito.app.model.ViewType;
import com.yoomiito.app.model.bean.BannerAndBgInfo;
import com.yoomiito.app.model.bean.BannerAndIconInfo;
import com.yoomiito.app.model.bean.EmptyInfo;
import com.yoomiito.app.model.bean.GoodsInfo;
import com.yoomiito.app.model.bean.HomeChosenAct;
import com.yoomiito.app.model.bean.HomeChosenGoods;
import com.yoomiito.app.model.bean.HomeVipInfo;
import com.yoomiito.app.model.bean.HotGoodsInfo;
import com.yoomiito.app.model.bean.UserInfo;
import com.yoomiito.app.model.home.FreeBuyActInfo;
import com.yoomiito.app.model.home.HomeHotActData;
import com.yoomiito.app.model.home.HomeVideo;
import com.yoomiito.app.model.home.PanicData;
import com.yoomiito.app.model.home.PanicGoods;
import com.yoomiito.app.model.home.PanicTime;
import com.yoomiito.app.model.home.VideoClipInfo;
import com.yoomiito.app.model.zhongtai.ZhongTaiData;
import com.yoomiito.app.present.home.HomeRecommendPresenter;
import com.yoomiito.app.ui.YouPinGoodsActivity;
import com.yoomiito.app.ui.goods.NewGoodsInfoActivity;
import com.yoomiito.app.ui.list.ThemeGoodsSortListActivity;
import com.yoomiito.app.ui.meituan.MeiTuanCouponActivity;
import com.yoomiito.app.ui.yijiayou.OilCardActivity;
import com.yoomiito.app.utils.ActTypeUtils;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.AllUtils;
import com.yoomiito.app.utils.CacheUtils;
import com.yoomiito.app.utils.Const;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.DialogManager;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.L;
import com.yoomiito.app.utils.LoginUtils;
import com.yoomiito.app.utils.RouterUtils;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.widget.dialog.FreeBuyDialog;
import com.yoomiito.app.widget.dialog.ShareBottomDialog;
import com.yoomiito.app.widget.dialog.SystemDialog;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.router.Router;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;

/**
 * 首页-----推荐
 */
public class HomeRecommendFragment extends BaseLazyFragment<HomeRecommendPresenter> {

    public static final String EXTRA_TEXT = "extra_text";
    @BindView(R.id.fm_recommend_smartRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.frameLayout)
    FrameLayout mFrameLayout;
//    @BindView(R.id.pushCardLayout)
//    PushCardLayout mPushCardLayout;

    private int bannerHeight = 300;
    private int page = 1;
    private HomeFragment parentFragment;
    private List<DelegateAdapter.Adapter> adapters = new LinkedList<>();
    public List<BannerAndIconInfo> datas = new ArrayList<>();
    public List<BannerAndIconInfo> bannerDatas = new ArrayList<>();
    public List<BannerAndIconInfo> iconDatas = new ArrayList<>();
    public List<BannerAndIconInfo> one2NDatas = new ArrayList<>();
    public List<BannerAndIconInfo> hotActDatas = new ArrayList<>();
    public List<HomeVipInfo> mVipInfos = new ArrayList<>();
    private List<GoodsInfo> goodsInfos = new ArrayList<>();
    private List<HomeVideo> mHomeVideos = new ArrayList<>();
    private HomeHotAdapter recommendAdapter;
    private HomeBannerAdapter bannerAdapter;
    private List<Object> bgUrls = new ArrayList<>();
    private HomeBaoPinAdapter baoPinAdapter;
    private HomeIconAdapter homeIconAdapter;
    private BannerAndBgInfo bannerAndBgInfo;
    private List<HotGoodsInfo> hotGoodsInfos;
    private ShareBottomDialog shareBottomDialog;
    private Context mHuoDongHeZiContext;
    private boolean mActHuoDongHeZi = true;
    private HomeVipAdapter homeVipAdapter;
    private HomePanicBuyTitleAdapter homePanicBuyTitleAdapter;
    private List<PanicGoods> mPanicGoods = new ArrayList<>();
    private HomePanicGoodsAdapter homePanicGoodsAdapter;
    private List<PanicTime> mPanicTimes;
    private EmptyInfo emptyInfo;
    private EmptyAdapter emptyAdapter;
    private int mCurrentClickPosition;
    private FreeBuyDialog freeBuyDialog;
    private FeaturedAreaAdapter mFeaturedAreaAdapter;
    private List<BannerAndIconInfo> mAreaInfos = new ArrayList<>();
    private SystemDialog systemDialog;
    private HomeChosenGoodsAdapter homeChosenGoodsAdapter;
    private List<HomeChosenAct> ChosenActDatas = new ArrayList<>();
    private HomeVideoClipAdapter homeVideoClipAdapter;
    private String mLastRecommndGoodsId = "";
    private SystemDialog oilCardDialog;
    public boolean showYouIcon = false;//记录底部bar显示的哪个图标 false---R.drawable.icon_home_active  true---R.drawable.icon_home_back
    private float mAlpha = 0;//透明度
    private BannerAndIconInfo mHandleIngMsg;
    private HomeActAdapter actAdapter;
    private HotActTitleAdapter titleAdapter;

    @Override
    public int getLayoutId() {
        return R.layout.fragment_test;
    }

    @Override
    public HomeRecommendPresenter newP() {
        return new HomeRecommendPresenter(App.mAppConfig);
    }

    @Override
    public void onSaveInstanceState(@NonNull Bundle outState) {
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            if (goodsInfos != null && goodsInfos.size() > 10) {
                getP().getRecommendGoods(page, mLastRecommndGoodsId);
            }
        });
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {

            page = 1;
            mLastRecommndGoodsId = "";
            if (disposable != null && !disposable.isDisposed()) {
                disposable.dispose();
            }
            disposable = null;
            down = true;
            getP().getBannerAndIcon();
            getP().hotAct();
            getP().getFeaturedArea();
            getP().getVideoList();
            getP().getRecommendGoods(page, mLastRecommndGoodsId);
            getP().getPanicGoods(0);

        });
        parentFragment = (HomeFragment) getParentFragment();
        initRvListener();
        initTangram();
        requestData();
    }

    private void requestData() {
        getP().getBannerAndIcon();
        getP().getFeaturedArea();
        getP().hotAct();
        getP().getRecommendGoods(page, mLastRecommndGoodsId);
        getP().getPanicGoods(0);
        getP().getFreeBuyActInfo();
        getP().getSystemInfo();
        getP().getVideoList();
    }

    private void requestData(int oo) {
        getP().getBannerAndIcon();
        getP().getFeaturedArea();
        getP().hotAct();
        getP().getRecommendGoods(page, mLastRecommndGoodsId);
        getP().getPanicGoods(0);
//        getP().getFreeBuyActInfo();
//        getP().getSystemInfo();
        getP().getVideoList();
    }

    private void requestData(String oo) {
        getP().getBannerAndIcon();
        getP().getFeaturedArea();
        getP().hotAct();
        getP().getRecommendGoods(page, mLastRecommndGoodsId);
        getP().getPanicGoods(0);
        getP().getFreeBuyActInfo();
//        getP().getSystemInfo();
        getP().getVideoList();
    }

    @Override
    protected void onStartLazy() {
        super.onStartLazy();
        if (mActHuoDongHeZi) {
            initHuoDongHeZi();
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
    }

    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);
        mRefreshLayout.finishLoadMore(true);
    }

    private void initTangram() {
        /*
        暂时不用
        TangramBuilder.InnerBuilder builder = TangramBuilder.newInnerBuilder(context);
        builder.registerCard(MultipleItem.TAB, );
        final TangramEngine engine = builder.build();
        engine.bindView(mRecyclerView);
        */
        VirtualLayoutManager layoutManager = new VirtualLayoutManager(context);
        mRecyclerView.setLayoutManager(layoutManager);

        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 0);//banner
        viewPool.setMaxRecycledViews(1, 5);//tab
        viewPool.setMaxRecycledViews(2, 0);//vip
        viewPool.setMaxRecycledViews(3, 5);//爆品
        viewPool.setMaxRecycledViews(4, 0);
        viewPool.setMaxRecycledViews(5, 10);//为你推荐  viewType=6  viewType=7已用
        viewPool.setMaxRecycledViews(8, 5);//抢购时间
        viewPool.setMaxRecycledViews(9, 5);//抢购商品
        viewPool.setMaxRecycledViews(10, 1);//抢购空
        viewPool.setMaxRecycledViews(11, 1);//特色专区
        viewPool.setMaxRecycledViews(12, 5);//精选活动  viewType=20  viewType=21已用
        viewPool.setMaxRecycledViews(13, 5);//短视频  viewType=22  viewType=23已用
        viewPool.setMaxRecycledViews(14, 6);//热门活动
        viewPool.setMaxRecycledViews(15, 1);//热门活动背景图
        mRecyclerView.setRecycledViewPool(viewPool);

        setBanner_1();
        setTab();
        /*首页去除成为VIP
          setVip();

         */
        setFeaturedArea();
        setHotAct();
        setVideoClip();
        setChosenAct();
        /*首页去除爆品
            setBaoPinGoods();
        */
        setPanicBuy();
        setEmpty();
        setRecommend();
        DelegateAdapter delegateAdapter = new DelegateAdapter(layoutManager, true);
        mRecyclerView.setAdapter(delegateAdapter);
        delegateAdapter.setAdapters(adapters);
    }


    private void setVideoClip() {
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        linearLayoutHelper.setDividerHeight(DensityUtil.dp2px(10));
        homeVideoClipAdapter = new HomeVideoClipAdapter(context,
                linearLayoutHelper,
                mHomeVideos,
                mRecyclerView.getRecycledViewPool());
        adapters.add(homeVideoClipAdapter);

    }

    /**
     * 精选活动
     */
    private void setChosenAct() {
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
//        linearLayoutHelper.setDividerHeight(DensityUtil.dp2px(10));
        homeChosenGoodsAdapter = new HomeChosenGoodsAdapter(context,
                linearLayoutHelper,
                ChosenActDatas,
                mRecyclerView.getRecycledViewPool(),
                (parentPosition, childPosition, isLookMore) -> {
                    //1淘宝商品；2礼包商品；3爆品商品；4优品商品；5区代商品
                    HomeChosenAct act = ChosenActDatas.get(parentPosition);
                    if (isLookMore) {
                        ThemeGoodsSortListActivity.Companion.start(context, act.getType() + "", act.getId() + "");
                        return;
                    }
                    if (childPosition != -1) {
                        HomeChosenGoods goods = act.getList().get(childPosition);
                        RouterUtils.toGoodsDetail(context, goods.getProductId() + "", goods.getType() == 1 ? Type.GoodsType.TaoBao : Type.GoodsType.BaoPin);
                    }
                });

        adapters.add(homeChosenGoodsAdapter);
    }

    //特色专区
    private void setFeaturedArea() {
//        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(2);
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(2);
        mFeaturedAreaAdapter = new FeaturedAreaAdapter(context, gridLayoutHelper, mAreaInfos);
        adapters.add(mFeaturedAreaAdapter);
        mFeaturedAreaAdapter.setOnItemClickListener(i -> {
            //'1淘宝商品2礼包商品3爆品商品4优品商品5区代商品',
//            BannerAndIconInfo info = mAreaInfos.get(i);
//            GoodsListActivity.Companion.start(context, info.getValue(), info.getValue_id(), info.getTitle());
            handleBannerOrIconType(mAreaInfos.get(i));
            return Unit.INSTANCE;
        });
    }

    private void setEmpty() {
        emptyInfo = new EmptyInfo();
        emptyInfo.setSize(0);
        emptyAdapter = new EmptyAdapter(context, emptyInfo);
        adapters.add(emptyAdapter);
    }

    //抢购
    private void setPanicBuy() {
//        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
//        HomeTitleAdapter titleAdapter = new HomeTitleAdapter(context, linearLayoutHelper, 2);
//        adapters.add(titleAdapter);
        mPanicTimes = getP().timeData(1);
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        homePanicBuyTitleAdapter = new HomePanicBuyTitleAdapter(context, 0, linearLayoutHelper, mRecyclerView.getRecycledViewPool(), mPanicTimes);
        homePanicBuyTitleAdapter.setItemClickListener(position -> {
            mCurrentClickPosition = mPanicTimes.get(position).getId();
            getP().getPanicGoods(mCurrentClickPosition);
        });
        adapters.add(homePanicBuyTitleAdapter);

        LinearLayoutHelper linearLayoutHelper1 = new LinearLayoutHelper();
//        linearLayoutHelper1.setDividerHeight(DensityUtil.dp2px(16));
        homePanicGoodsAdapter = new HomePanicGoodsAdapter(context, linearLayoutHelper1, mPanicGoods);
        homePanicGoodsAdapter.setOnItemClickLisenter((position, isShare) -> {
            RouterUtils.toGoodsDetail((MainActivity) context, mPanicGoods.get(position).getItemid(), AllCode.TaoBao);
        });
        adapters.add(homePanicGoodsAdapter);
    }

    private void setBanner_1() {
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        bannerAdapter = new HomeBannerAdapter(context, linearLayoutHelper, null);
        adapters.add(bannerAdapter);
        bannerAdapter.setItemClickListener(position -> {
            //类型0，单纯图片，1 h5地址，2 商品类目列表商品界面，3, 9.9包邮，4 淘宝地址，5 淘抢购 6 好裆裤商品列表 7优品专区 8 优品爆品礼包商品详情
            //目前 0 1 4 7
            BannerAndIconInfo iconInfo = bannerDatas.get(position);
            handleBannerOrIconType(iconInfo);
        });
    }

    //设置爆品
    private void setBaoPinGoods() {
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        baoPinAdapter = new HomeBaoPinAdapter(context, linearLayoutHelper, mRecyclerView.getRecycledViewPool(), new HomeBaoPinItemAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position, boolean isLookMore) {
                if (position != -1) {
                    HotGoodsInfo info = hotGoodsInfos.get(position);
                    RouterUtils.toGoodsDetail((MainActivity) context, String.valueOf(info.getId()), AllCode.BaoPin);
                    return;
                }
                if (isLookMore) {
                    String title = "爆品专区";
//                    if (CurrentUser.mUserInfo.getCompany_id() == 1) {
//                        title
//                    } else {
//                        title = "瑰秘汇 · 爆品专区";
//                    }
                    Router.newIntent(context)
                            .putString(Constant.DATA, title)
                            .putInt(Constant.TYPE, AllCode.BaoPin)
                            .to(YouPinGoodsActivity.class)
                            .launch();
                }
            }
        });
        adapters.add(baoPinAdapter);

    }


    private void setRecommend() {
//        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
//        HomeTitleAdapter titleAdapter = new HomeTitleAdapter(context, linearLayoutHelper, 1);
        GoodsDetailTitleAdapter titleAdapter = new GoodsDetailTitleAdapter(context, "热门商品");
        adapters.add(titleAdapter);

//        LinearLayoutHelper linearLayoutHelper_1 = new LinearLayoutHelper();
//        linearLayoutHelper_1.setDividerHeight(DensityUtil.dp2px(16));

        LinearLayoutHelper linearLayoutHelper1 = new LinearLayoutHelper();
        recommendAdapter = new HomeHotAdapter(context, linearLayoutHelper1, goodsInfos);
        adapters.add(recommendAdapter);
        recommendAdapter.setOnItemClickLisenter((position, isShare) -> {//进入商品详情
            GoodsInfo info = goodsInfos.get(position);
//            if (isShare) {
//                RouterUtils.toShareGoods((MainActivity) context, info.getId(), AllCode.TaoBao);
//            } else {
//                RouterUtils.toGoodsDetail((MainActivity) context, info.getId(), AllCode.TaoBao);
//            }
            NewGoodsInfoActivity.Companion.toGoodsInfo(context, String.valueOf(info.getId()), "2");
        });
        if (goodsInfos == null || goodsInfos.size() <= 10) {
            if (page == 1)
                mRefreshLayout.setEnableLoadMore(false);
        }
    }

    private void setHotAct() {
//        String[] s = {"https://mimitao-cdn.aijiamai.com/FsycazOP4EJowWHkCry6f8NgKqxO", "https://mimitao-cdn.aijiamai.com/FisRAIXepKWWRLPSAxNywZ7UL15Z",
//                "https://mimitao-cdn.aijiamai.com/Fkgl6AjUJdJ8LVJQVwaHC7iMMKx_", "https://mimitao-cdn.aijiamai.com/FuIEmZG2ZE4ENIXJRdk3BioL0VIb",
//                "https://mimitao-cdn.aijiamai.com/FsycazOP4EJowWHkCry6f8NgKqxO", "https://mimitao-cdn.aijiamai.com/FisRAIXepKWWRLPSAxNywZ7UL15Z",
//                "https://mimitao-cdn.aijiamai.com/Fkgl6AjUJdJ8LVJQVwaHC7iMMKx_", "https://mimitao-cdn.aijiamai.com/FuIEmZG2ZE4ENIXJRdk3BioL0VIb",};
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        linearLayoutHelper.setMargin(0, DensityUtil.dp2px(12), 0, 0);
        titleAdapter = new HotActTitleAdapter(context, linearLayoutHelper, null, data -> {
            BannerAndIconInfo bannerAndIconInfo = new BannerAndIconInfo();
            bannerAndIconInfo.setTitle(data.getTitle());
            bannerAndIconInfo.setType(data.getType());
            bannerAndIconInfo.setValue(data.getValue());
            bannerAndIconInfo.setValue_id(data.getValue_id());
            ActTypeUtils.INSTANCE.handleActFromType(context, bannerAndIconInfo);
            return Unit.INSTANCE;
        });
        adapters.add(titleAdapter);

        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(2);
//        gridLayoutHelper.setMargin(DensityUtil.dp2px(12), 0, DensityUtil.dp2px(12), 0);
//        gridLayoutHelper.setVGap(DensityUtil.dp2px(8));// 控制子元素之间的垂直间距
//        gridLayoutHelper.setHGap(DensityUtil.dp2px(7));// 控制子元素之间的水平间距
        gridLayoutHelper.setAutoExpand(false);
        actAdapter = new HomeActAdapter(context, gridLayoutHelper, null);
        actAdapter.setOnItemClickLisenter(info -> ActTypeUtils.INSTANCE.handleActFromType(context, info));
        adapters.add(actAdapter);
    }
/*

    private void setOneToN() {
        one2NDatas.add(new BannerAndIconInfo());
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        HomeOneToNAdapter oneToNAdapter = new HomeOneToNAdapter(context,linearLayoutHelper , one2NDatas);
        adapters.add(oneToNAdapter);
    }

    //需求不需要了 代码不删除
    private void setVip() {
        HomeVipInfo homeVipInfo = new HomeVipInfo();
        homeVipInfo.setShow(UserInfoConfig.getCompanyId() == 1 && UserInfoConfig.getRoleId() <= LevelType.VIP_4);
        mVipInfos.add(homeVipInfo);
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        homeVipAdapter = new HomeVipAdapter(context, linearLayoutHelper, mVipInfos);
        adapters.add(homeVipAdapter);
        homeVipAdapter.setOnClickListener(v -> {
            ((MainActivity) context).switchFm(1);
        });
    }
 */

    private void setTab() {
        GridLayoutHelper gridLayoutHelper = new GridLayoutHelper(5);
//        gridLayoutHelper.setVGap(DensityUtil.dp2px(15));
        homeIconAdapter = new HomeIconAdapter(context, gridLayoutHelper, iconDatas);
        adapters.add(homeIconAdapter);
        homeIconAdapter.setItemClickListener(position -> {
            BannerAndIconInfo iconInfo = iconDatas.get(position);
            handleBannerOrIconType(iconInfo);
        });
    }

    /**
     * 处理banner和小图标的点击事件
     * if (App.mAppConfig.getIsLogin() && "1".equals(UserInfoConfig.getUser().getIsOil())) {
     * OilCardActivity.Companion.start(context);
     * } else {
     * showOilCardDialog();
     * }
     *
     * @param iconInfo
     */
    private void handleBannerOrIconType(BannerAndIconInfo iconInfo) {
        if (iconInfo != null)
            ActTypeUtils.INSTANCE.handleActFromType((MainActivity) context, iconInfo);
    }

    /**
     * recyclerView初始化---1
     */
    private void initRvListener() {
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int totalDy = 0;

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                totalDy += dy;
                if (totalDy <= bannerHeight) {
                    mAlpha = (float) totalDy / bannerHeight;
                    if (mAlpha < 0) mAlpha = 0;
                } else {
                    mAlpha = 1;
                }
                changeTopSearchBg();
                showYouIcon = totalDy > App.mHeightPx / 2;
                ((MainActivity) context).changeYouMiIv(showYouIcon);
            }
        });
    }

    public void changeTopSearchBg() {
//        parentFragment.top_search_ll.setBackgroundColor(ColorUtils.blendARGB(Color.TRANSPARENT
//                , ContextCompat.getColor(context, R.color.color_FF035B), mAlpha));
    }

    /**
     * 对首页banner 和 活动图标 数据分发
     *
     * @param banners
     */
    public void bannerData(ArrayList<BannerAndIconInfo> banners) {
        bannerDatas.clear();
        bgUrls.clear();
        bannerDatas.addAll(banners);
        for (int i = 0; i < bannerDatas.size(); i++) {
            bgUrls.add(banners.get(i).getBg_image_url());
        }

        bannerAdapter.setNewData(new BannerAndBgInfo((ArrayList) bannerDatas, bgUrls));
    }

    public void setTabData(List<BannerAndIconInfo> datas) {
        iconDatas.clear();
        iconDatas.addAll(datas);
        homeIconAdapter.notifyDataSetChanged();
    }

    public void setChosenActData(List<HomeChosenAct> datas) {
        if (datas == null) return;
        ChosenActDatas.clear();
        ChosenActDatas.addAll(datas);
        homeChosenGoodsAdapter.notifyDataSetChanged();
    }

    public void setBaoPinData(List<HotGoodsInfo> hotGoodsInfos) {
        if (hotGoodsInfos != null && hotGoodsInfos.size() > 0) {
            for (HotGoodsInfo info : hotGoodsInfos) {
                info.setViewType(7);
            }
            hotGoodsInfos.add(new HotGoodsInfo(6));
        }
        this.hotGoodsInfos = hotGoodsInfos;
        baoPinAdapter.setData(hotGoodsInfos);
    }

    public void setHotActData(HomeHotActData data) {
        L.i("data:  " + data + "    " + (data != null));
        if (data != null && !TextUtils.isEmpty(data.getStatus()) && data.getStatus().equals("Y")) {
            for (BannerAndIconInfo iconInfo : data.getLists()) {
                iconInfo.setBgcolor(data.getBgcolor());
                iconInfo.setValue_id(iconInfo.getValue_id());
            }
            titleAdapter.setNewDatas(TextUtils.isEmpty(data.getImageUrl()) ? null : data);
            actAdapter.newDatas(data.getLists());
        } else {
            titleAdapter.setNewDatas(null);
            actAdapter.newDatas(null);
        }
    }

    public void setFeaturedAreaData(List<BannerAndIconInfo> areaInfos) {
        mAreaInfos.clear();
        mAreaInfos.addAll(areaInfos);
        mFeaturedAreaAdapter.notifyDataSetChanged();
    }

    boolean down = false;
    int mNextPanicType;
    Disposable disposable = null;

    private void startCountDown(long mDownTime) {
        if (disposable == null) {
            disposable = Observable.interval(0, 1, TimeUnit.SECONDS)
//                    .compose(bindToLifecycle())
                    .take(mDownTime + 1)
                    .observeOn(Schedulers.io())
                    .doOnNext(aLong -> {
//                        Log.i("YOM","S:"+aLong);
                            }
                    )
                    .doOnComplete(() -> {
//                        Log.i("YOM","开始请求");
                        down = true;
                        disposable = null;
                        getP().getPanicGoods(0);
                    })
                    .subscribe();
        }
    }

    //快抢
    public void setPanicGoodsData(PanicData panicData) {
        if (panicData.getLimit()) {
            mNextPanicType = panicData.getHour_type_now() + 1;
            startCountDown(panicData.getNext_time() - panicData.getTime());
            if (homePanicBuyTitleAdapter.getItemCount() == 0) {//只绘制一次
                getP().timeData(panicData.getHour_type_now());
                homePanicBuyTitleAdapter.setItemSize(1);
                homePanicBuyTitleAdapter.setTimePosition(panicData.getHour_type_now());
                homePanicBuyTitleAdapter.notifyDataSetChanged();
            } else if (down) {
                getP().timeData(panicData.getHour_type_now());
                homePanicBuyTitleAdapter.setTimePosition(panicData.getHour_type_now());
                homePanicBuyTitleAdapter.setUpdate(true);
                homePanicBuyTitleAdapter.notifyDataSetChanged();
                down = false;
            } else {
                homePanicBuyTitleAdapter.setUpdate(false);
            }
            homePanicGoodsAdapter.setShowHotFlag(panicData.getHour_type_now() >= panicData.getHour_type());
            mPanicGoods.clear();
            mPanicGoods.addAll(panicData.getData());
            homePanicGoodsAdapter.notifyDataSetChanged();
//            Log.i("YOM","刷新数据了");
            if (panicData.getData() == null || panicData.getData().size() == 0) {//商品为空

                emptyInfo.setSize(1);
                if (panicData.getHour_type_now() < panicData.getHour_type()) {
                    emptyInfo.setIvResId(R.drawable.default_empty_1);
                    emptyInfo.setContent_1("该场次商品正在准备中");
                    emptyInfo.setContent_2("请稍后再来…");
                } else {
                    emptyInfo.setIvResId(R.drawable.default_empty);
                    emptyInfo.setContent_1("商品已抢光");
                }
                emptyAdapter.setSize(1);
                emptyAdapter.notifyDataSetChanged();
            } else {
                emptyAdapter.setSize(0);
                emptyAdapter.notifyDataSetChanged();
            }
        }
    }

    public void setPanicGoodsEmpty() {
        emptyInfo.setSize(1);
        if (mNextPanicType - 1 < mCurrentClickPosition) {
            emptyInfo.setIvResId(R.drawable.default_empty_1);
            emptyInfo.setContent_1("该场次商品正在准备中");
            emptyInfo.setContent_2("请稍后再来…");
        } else {
            emptyInfo.setIvResId(R.drawable.default_empty);
            emptyInfo.setContent_1("商品已下架");
        }
        emptyAdapter.setSize(1);
        emptyAdapter.notifyDataSetChanged();
        mPanicGoods.clear();
        homePanicGoodsAdapter.notifyDataSetChanged();
    }

    public void recommendGoods(List<GoodsInfo> infos, boolean isSuccess) {
        if (infos != null && infos.size() > 0) {
            mLastRecommndGoodsId = infos.get(infos.size() - 1).getId();
        }
        if (page == 1) {
            goodsInfos.clear();
            mRefreshLayout.finishRefresh(true);
        } else {
            if (infos == null || infos.size() == 0) {
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                mRefreshLayout.finishLoadMore(isSuccess);
            }
        }
        if (isSuccess) {
            if (infos != null && infos.size() != 0) {
                page++;
            }
            goodsInfos.addAll(infos);
            recommendAdapter.notifyDataSetChanged();
        }
    }

    public void showVideoList(List<VideoClipInfo> infos) {
        mHomeVideos.clear();
        if (infos == null || infos.size() == 0) {
            homeVideoClipAdapter.notifyDataSetChanged();
            return;
        }
        HomeVideo homeVideo = new HomeVideo();
        List<ViewType<VideoClipInfo>> datas = new ArrayList<>();
        mHomeVideos.add(homeVideo);
        homeVideo.setData(datas);
        for (VideoClipInfo info : infos) {
            datas.add(new ViewType<VideoClipInfo>(23, info));
        }
        datas.add(new ViewType<VideoClipInfo>(22, null));
        homeVideoClipAdapter.notifyDataSetChanged();
    }

    public void setFreeBuyGoods(FreeBuyActInfo freeBuyActInfo) {
        if (freeBuyActInfo == null) {
            DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getFREEORDER(), null);
            return;
        }
        if (freeBuyDialog == null) {
            freeBuyDialog = new FreeBuyDialog(context);
            freeBuyDialog.setFreeBuyActInfo(freeBuyActInfo);
            freeBuyDialog.setOnViewClickListener(view -> {
                NewFreeBuyActivity.start(context, freeBuyActInfo.getId());
                freeBuyDialog.dismiss();
            });
        }
        DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getFREEORDER(), freeBuyDialog);
//        freeBuyDialog.show();
    }

    public void setSystemDialog(BannerAndIconInfo info) {
//        if (info == null || (info.getShow_type() == 2 && CacheUtils.INSTANCE.showed(Const.Common.ConfigDialogType, info))) {
//            DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getSYSTEMDIALOG(), null);
//            return;
//        }

        if (info == null){
            return;
        }
        if (systemDialog == null) {
            systemDialog = new SystemDialog(context);
            systemDialog.setOnViewClickListener(view -> {
                mHandleIngMsg = info;
                handleBannerOrIconType(info);
                systemDialog.dismiss();
            });
        }
        systemDialog.setSystemDialogInfo(info);
        systemDialog.show();
//        DialogManager.Companion.getMInstance().addManager(DialogManager.Companion.getMInstance().getSYSTEMDIALOG(), systemDialog);
    }

//    public void addDialogManager(AllDialogModel model) {
//        L.i("获取到弹窗数据");
//
//        setFreeBuyGoods(model.getFreeOrderModel());
//        setSystemDialog(model.getSystemModel());
//    }

    public void toAddOil() {
        dismissLoading();
        OilCardActivity.Companion.start(context, OilCardActivity.FirstGetFreeOilCard);
    }

    public void toAddOilError(int code) {
        dismissLoading();
        switch (code) {
            case 401://未登录
                LoginUtils.INSTANCE.toOneKeyLogin((MainActivity) context);
                break;
            case 501://已领取
                OilCardActivity.Companion.start(context, "");
                break;
        }
    }

    public void showOilCardDialog() {
        String versionName = AllUtils.getVersionInfo().versionName;
        BannerAndIconInfo bannerAndIconInfo = new BannerAndIconInfo();
        bannerAndIconInfo.setBg_image_url("https://mimitao-cdn.aijiamai.com/static/tc@3x.png?" + versionName);
        bannerAndIconInfo.setImage_url("https://mimitao-cdn.aijiamai.com/static/tc@3x.png?" + versionName);
        if (oilCardDialog == null) {
            oilCardDialog = new SystemDialog(context);
            oilCardDialog.setBtnGoResId(R.drawable.icon_free_oil_card);
            oilCardDialog.setmGoClickListener(view -> {
                //获取加油卡
                if (App.mAppConfig.getIsLogin()) {
                    oilCardDialog.dismiss();
                    if ("1".equals(UserInfoConfig.getUser().getIsOil())) {
                        OilCardActivity.Companion.start(context, "");
                    } else {
                        showLoading();
                        getP().getFreeOilCard();
                    }
                } else {
                    //去登陆
                    LoginUtils.INSTANCE.toOneKeyLogin((MainActivity) context);
                }

            });
        }
        oilCardDialog.setSystemDialogInfo(bannerAndIconInfo);
        oilCardDialog.show();
    }

    public void setZhongTai(ZhongTaiData data) {
        dismissLoading();
        WebViewActivity.start(context, data.getUrl());
    }

    public void setCreditCard(CreditCard creditCard) {
        dismissLoading();
        if (!TextUtils.isEmpty(creditCard.getUrl())) {
            WebViewActivity.start(context, creditCard.getUrl(), Const.Url.CreditCard);
        }
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (AllCode.LoginSuccess.equals(eventMessage.getEventType())) {
            DialogManager.Companion.getMInstance().showDialogAgain(DialogManager.Companion.getMInstance().getFREEORDER());
            page = 1;
            mLastRecommndGoodsId = "";
//            getP().getBannerAndIcon();
//            getP().getRecommendGoods(page,mLastRecommndGoodsId);
//            getP().getFreeBuyActInfo();
            requestData("");
            if (oilCardDialog != null && oilCardDialog.isShowing() && "1".equals(UserInfoConfig.getUser().getIsOil())) {
                oilCardDialog.dismiss();
                OilCardActivity.Companion.start(context, "");
            }
            if (mHandleIngMsg != null) {
                handleBannerOrIconType(mHandleIngMsg);
            }
        }
        if (AllCode.LoginOut.equals(eventMessage.getEventType())) {
            mHandleIngMsg = null;
            page = 1;
            mLastRecommndGoodsId = "";
//            getP().getBannerAndIcon();
//            getP().getRecommendGoods(page,mLastRecommndGoodsId);
            requestData(0);
        }
        if (AllCode.SHOW_DIALOG.equals(eventMessage.getEventType())) {
            DialogManager.Companion.getMInstance().show();
        }
        if (Type.EventMsgType.HomeScrollTop.equals(eventMessage.getEventType())) {
            mRecyclerView.smoothScrollToPosition(0);
        }
        if (Type.EventMsgType.CustomAdMeg.equals(eventMessage.getEventType())) {
            mHandleIngMsg = com.alibaba.fastjson.JSONObject.parseObject(eventMessage.getMsg(), BannerAndIconInfo.class);
            handleBannerOrIconType(mHandleIngMsg);
        }
        if (Type.EventMsgType.HandleOilCardData.equals(eventMessage.getEventType())) {
            if (App.mAppConfig.getIsLogin() && "1".equals(UserInfoConfig.getUser().getIsOil())) {
                OilCardActivity.Companion.start(context, "");
            } else {
                showOilCardDialog();
            }
        }//油卡

        if (Type.EventMsgType.HandleMeiTuanData.equals(eventMessage.getEventType())) {
            if (App.mAppConfig.getIsLogin()) {
                MeiTuanCouponActivity.Companion.start(context);
            } else {
                LoginUtils.INSTANCE.toOneKeyLogin((MainActivity) context);
            }
        }//美团
        if (Type.EventMsgType.HandleZhongTaiData.equals(eventMessage.getEventType())) {
            if (App.mAppConfig.getIsLogin()) {
                showLoading();
                getP().zhongtaiUrl();
            } else {
                LoginUtils.INSTANCE.toOneKeyLogin((MainActivity) context);
            }
        }//中泰
        if (Type.EventMsgType.HandleCreditCardData.equals(eventMessage.getEventType())) {
            if (App.mAppConfig.getIsLogin()) {
                showLoading();
                getP().creditCardUrl();
            } else {
                LoginUtils.INSTANCE.toOneKeyLogin(context);
            }
        }//信用卡
    }

    @Override
    protected void onStopLazy() {
        super.onStopLazy();
        if (App.mAppConfig.getIsLogin()) {
            mHandleIngMsg = null;
        }
    }

    private void initHuoDongHeZi() {
        if (App.mAppConfig == null ||
                App.mAppConfig.mCurrentUser == null ||
                App.mAppConfig.mCurrentUser.mUserInfo == null) return;

        UserInfo userInfo = App.mAppConfig.mCurrentUser.mUserInfo;

//        HzSDKBean hzSDKBean = new HzSDKBean();
//        //活动触发条件必填 设置活动触发条件可以是自定义的event字符串
//        hzSDKBean.setEvent("startup");
//        //设置用户的唯一名称或者用户的 id 必填
//        hzSDKBean.setUserName(String.valueOf(userInfo.getId()));
//        //设置手机号码 必填
//        hzSDKBean.setMobile(userInfo.getMobile());
//        hzSDKBean.setNickName(userInfo.getName());
//        JSONObject jsonObject = new JSONObject();
//        try {
//            jsonObject.put("level", String.valueOf(userInfo.getRole_id()));
//            jsonObject.put("company", String.valueOf(userInfo.getCompany_id()));
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//        HashMap<String, String> params = new HashMap<>();
//        params.put("extra_params", jsonObject.toString());
//        hzSDKBean.setReserveParams(params);
////        hzSDKBean.setEvent(JSONObject.toJSONString(params));
//        //用于投放活动设置活动位置 key
////        hzSDKBean.setPositionKey("");
//        //设置h5的返回图标
//        hzSDKBean.setHzBackIcon(R.mipmap.back);
//        //设置h5的背景颜色
//        hzSDKBean.setHzBarBackground(getResources().getColor(R.color.color_white));
//        //设置 h5页面的标题颜色
//        hzSDKBean.setHzBarTitleColor(Color.BLACK);
//        //触发的小图标是否自动透明
//        hzSDKBean.setIconAutoTransparent(false);
//        //触发的小图标是否自动隐藏
//        hzSDKBean.setIconAutoHidden(false);
//        //触发的小图标是否自动靠边
//        hzSDKBean.setIconAutoPullOver(true);
//        //设置打开活动的相关回调
//        hzSDKBean.setHzSDKListener(new HzSDKListener() {
//
//
//            /**
//             *
//             * @param context
//             * @param s 活动分享链接地址
//             * @param s1 活动标题
//             * @param s2 活动内容
//             * @param s3 活动分享图标
//             * @param s4 用于统计分享成功的链接
//             */
//            @Override
//            public void onWebViewShareClick(Context context, String s, String s1, String s2, String s3, String s4) {
//                mHuoDongHeZiContext = context;
//                //活动分享事件
//                //用户可以做自己的调用自己的分享功能
//                ShowShareDialog(context, s, s1, s2, s3);
//            }
//
//            @Override
//            public void onWebViewFinish() {
//                //活动页面关闭回调
//                if (mHuoDongHeZiContext != null) {
//                    UMShareAPI.get(mHuoDongHeZiContext).release();
//                    mHuoDongHeZiContext = null;
//                }
//            }
//
//            @Override
//            public boolean onWebViewOpen(Context context, String s) {
//                //点击活动图标触发打开活动页面时的回调
//                //用户可以设置为false 自己做跳转动作
//                return true;
//            }
//
//            @Override
//            public boolean dismissWithTrigger(boolean b, HzSDKTriggerView hzSDKTriggerView) {
//                //return false 表示点击小图标后图标不消失
//                return true;
//            }
//
//            /**
//             * 触发请求失败的回调,便于用户判断是否触发请求成功
//             * 请求失败 用户可以再次触发
//             * @param s
//             */
//            @Override
//            public void requestError(String s) {
//
//            }
//
//            @Override
//            public void requestSuccess(String s) {
//                // 触发请求成功的回调,用于用户感知触发请求成功
//                mActHuoDongHeZi = false;
//            }
//
//            @Override
//            public void returnFloatView(HzSDKFloatView hzSDKFloatView) {
//
//            }
//        });
//        HzSDK.getInstance().triggerWithViewGroup(context, mFrameLayout, hzSDKBean);
    }

//    public void ShowShareDialog(Context context, String shareUrl, String shareTitle, String shareContent, String shareIcon) {
//        if (shareBottomDialog == null) {
//            shareBottomDialog = new ShareBottomDialog(context);
//            shareBottomDialog.setOnShareItemClickListener(type -> {
//                switch (type) {
//                    case 1://微信
//                        UMengShareUtils.shareWX((H5) context, shareContent, shareUrl, shareTitle, shareIcon);
//                        break;
//                    case 2://朋友圈
//                        UMengShareUtils.shareWXCircle((H5) context, shareContent, shareUrl, shareTitle, shareIcon);
//                        break;
//                }
//                shareBottomDialog.dismiss();
//            });
//        }
//        shareBottomDialog.show();
//    }

}
